package com.qf.controller;


import com.qf.constant.AppConstant;
import com.qf.entity.DevUser;
import com.qf.enums.AppEnum;
import com.qf.exception.AppException;
import com.qf.from.RegisterDevUser;
import com.qf.service.DevUserService;
import com.qf.shiro.AppToken;
import com.qf.util.ResultVOUtil;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 *
 * 用户模块
 *
 */

@Controller
@Slf4j
@RequestMapping("/dev/user")
public class DevUserController {

    @Autowired
    private DevUserService devUserService;

    //跳转登录页面
    @GetMapping("/login-ui")
    public String loginUI(){
        return "dev/user/login";
    }

    //跳转注册页面
    @GetMapping("/register-ui")
    public String registerUI(){
        return "dev/user/register";
    }

    //异步校验用户名
    @PostMapping("/checkUsername")
    @ResponseBody
    public ResultVO checkUsername(String devName){

        if (StringUtils.isEmpty(devName)){
            log.info("【用户注册】初入参数异常 devName={}",devName);
            return ResultVOUtil.error(AppEnum.PARAM_ERROR);
        }

        devUserService.checkUsername(devName);

        return ResultVOUtil.error(0,"用户名可用");
    }

    //用户注册
    @PostMapping("/register")
    @ResponseBody
    public ResultVO register(@Valid RegisterDevUser registerDevUser,
                             BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【用户注册】传入参数异常 registerDevUser={} msg={}",registerDevUser,msg);
            return ResultVOUtil.error(AppEnum.PARAM_ERROR.getCode(),msg);
        }

        DevUser devUser = new DevUser();
        BeanUtils.copyProperties(registerDevUser,devUser);

        devUserService.register(devUser);


        return ResultVOUtil.ok();
    }

    //账号激活
    @GetMapping("/active")
    public String active(String email, String code, Model model){
        if (StringUtils.isEmpty(email)||StringUtils.isEmpty(code)){
            log.info("【用户注册】 账号激活传入参数有误！");
            model.addAttribute(AppConstant.ACTIVEKEY,"链接无法识别，请重新激活！");
            return AppConstant.ACTIVEURL;
        }

        try {
            devUserService.activeEmail(email,code);
        } catch (AppException e) {
            e.printStackTrace();
            log.error("【用户注册】 激活账号失败 e = {}",e);
            model.addAttribute(AppConstant.ACTIVEKEY,e.getMessage());
            return AppConstant.ACTIVEURL;

        }

        model.addAttribute(AppConstant.ACTIVEKEY,"恭喜你激活成功<a style='color:blue;' href='/dev/user/login-ui'>点击跳转登录</a>");

        return AppConstant.ACTIVEURL;
    }

    //再次激活跳转页面
    @GetMapping("/nextActive-ui")
    public String nextActiveUI(){

        return "dev/user/active";
    }

    //再次激活
    @PostMapping("/nextActive")
    @ResponseBody
    public ResultVO nextActive(String devUsername,String devEmail){

        if (StringUtils.isEmpty(devUsername)||StringUtils.isEmpty(devEmail)){
            log.info("【用户注册】传入参数异常 devUsername={},devEmail={}",devUsername,devEmail);
            return ResultVOUtil.error(AppEnum.PARAM_ERROR.getCode(),"参数不能为空！");
        }

        devUserService.nextActiveEmail(devUsername,devEmail);

        return ResultVOUtil.ok("激活邮件发送成功！");
    }

    //用户登录
    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(String devUsername,String devPassword){
        if (StringUtils.isEmpty(devUsername)||StringUtils.isEmpty(devPassword)){
            log.info("【用户注册】 登录时传入参数有误！用户名或密码不能为空");
            return ResultVOUtil.error(AppEnum.PARAM_ERROR.getCode(),"用户名或密码不能为空！");
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new AppToken(devUsername,devPassword,AppConstant.DEV_USER));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            log.info("【用户登录】用户名错误！ username={} password={}",devUsername,devPassword);
            throw new AppException(AppEnum.LOGIN_USERNAME_ERROR);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            log.info("【用户登录】密码错误！ username={} password={}",devUsername,devPassword);
            throw new AppException(AppEnum.LOGIN_PASSWORD_ERROR);
        } catch (AppException e) {
            e.printStackTrace();
            log.info("【用户登录】账号未激活！ username={} password={}",devUsername,devPassword);
            throw new AppException(AppEnum.DEVUSER_NOT_ACTIVE);
        }
        return ResultVOUtil.ok();
    }


}
